package app.auto.runner.base.utility;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.aliang.auto.R;
import com.squareup.picasso.Picasso;


import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import app.auto.AndroidInstance;
import app.auto.runner.base.MapViewConf;
import app.auto.runner.base.intf.FunCallback;
import app.auto.runner.base.intf.json.JsonToMapUtils;
import app.auto.runner.base.type.DateUtil;

public class FillUtil extends AndroidInstance {


    private FunCallback transfer;
    private List liststring;

    public FillUtil setUrlTransfer(FunCallback funCallback) {
        this.transfer = funCallback;
        return this;
    }

    ListView lv;

    public FillUtil setListView(ListView lv) {
        this.lv = lv;
        return this;
    }

    FunCallback finalcallback;

    public FillUtil setFinalcallback(FunCallback finalcallback) {
        this.finalcallback = finalcallback;
        return this;
    }


    FunCallback clickCallback;

    public FillUtil setClickCallback(FunCallback clickCallback) {
        this.clickCallback = clickCallback;
        return this;
    }

    public FillUtil fillList(ListView lv,final List liststring, FunCallback finalcallback, final FunCallback clickCallback) {
        setListView(lv);
        this.liststring = liststring;
        setFinalcallback(finalcallback);
        setClickCallback(clickCallback);
        set();
        return this;
    }

    public FillUtil setListPs(final List liststring, FunCallback finalcallback, final FunCallback clickCallback) {
        this.liststring = liststring;
        setFinalcallback(finalcallback);
        setClickCallback(clickCallback);
        return this;
    }


    public FillUtil set() {
        setprivate();
        return this;
    }

    private FillUtil setprivate() {
        if (lv.getAdapter() == null) {

            lv.setAdapter(new BaseAdapter() {

                Set<Integer> loadedcounts = new TreeSet<Integer>();

                @Override
                public int getCount() {
                    return liststring.size();
                }

                @Override
                public Object getItem(int position) {
                    return liststring.get(position);
                }

                @Override
                public long getItemId(int position) {
                    return 0;
                }

                @Override
                public View getView(final int position, View convertView, ViewGroup parent) {
//                    if (position == getCount() - 3) {
//                        if (!loadedcounts.contains(position)) {
//                            loadedcounts.add(position);
//                            if (finalcallback != null) {
//                                finalcallback.onCallback(null, null);
//                            }
//                        }
//                    }
                    if (convertView == null) {
                        convertView = LayoutInflater.from(lv.getContext()).inflate(R.layout.image_item, null);
                    }

                    Object data = getItem(position);
                    if (data instanceof String) {

                        String item = (String) data;


                        if (TextUtils.isEmpty(item.split("&&")[0])) {
                            convertView.findViewById(R.id.imageNet).setVisibility(View.GONE);
                        } else {
                            convertView.findViewById(R.id.imageNet).setVisibility(View.VISIBLE);
                            Picasso.with(getContext()).load(item.split("&&")[0]).config(Bitmap.Config.RGB_565).into(((ImageView) convertView.findViewById(R.id.imageNet)));
                        }

                        ((TextView) convertView.findViewById(R.id.name)).setText(item.split("&&")[1]);
                    } else if (data instanceof Map) {
                        Map m = (Map) data;
                        if (TextUtils.isEmpty((CharSequence) m.get(imageField))) {
                            convertView.findViewById(R.id.imageNet).setVisibility(View.GONE);
                        } else {
                            convertView.findViewById(R.id.imageNet).setVisibility(View.VISIBLE);

                            String url = "";
                            if (m.get(imageField).toString().contains("http")) {
                                url = m.get(imageField).toString();
                            } else {
                                if (transfer != null) {
                                    transfer.simpleRun(m.get(imageField));
                                    url = (String) transfer.getResult();
                                }
                            }
                            try {
//                                ImageView iv = ((ImageView) convertView.findViewById(R.id.imageNet));
//                                .centerCrop().resize(iv.getLayoutParams().width, iv.getLayoutParams().height)

//                                int width = ((ImageView) convertView.findViewById(R.id.imageNet)).getLayoutParams().width;
//                                int height = ((ImageView) convertView.findViewById(R.id.imageNet)).getLayoutParams().height;
//                                if (width > 0 && height > 0) {
//                                    Picasso.with(getContext()).load(url).resize(width, height).centerCrop().config(Bitmap.Config.RGB_565).into(((ImageView) convertView.findViewById(R.id.imageNet)));
//                                } else {

                                final String finalUrl = url;
                                final View finalConvertView = convertView;
//                                new Thread() {
//                                    @Override
//                                    public void run() {
//                                        super.run();
//                                        Drawable m = null;
//                                        try {
//                                            m = new BitmapDrawable(getImageBitmap(finalUrl));
////                                            m = Glide.with(getContext()).setDefaultRequestOptions(new RequestOptions().format(DecodeFormat.PREFER_RGB_565)
////                                                    .disallowHardwareConfig()).load(Uri.parse(finalUrl)).submit().get();
//                                        } catch (Exception e) {
//                                            e.printStackTrace();
//                                        }
////                                        catch (ExecutionException e) {
////                                            e.printStackTrace();
////                                        }
//                                        final Drawable finalM = m;
//                                        String path = "";
//                                        if (finalM == null) {
//                                            return;
//                                        }
////                                        BitmapUtil.saveBitmap(((BitmapDrawable) finalM).getBitmap(), new File(path = StorageUtil.getPrimaryStoragePath(getContext()) + "/" + finalUrl.replace(":", "_").replaceAll("/", "_")));
//                                        final String finalPath = path;
//                                        new Handler(Looper.getMainLooper(), new android.os.Handler.Callback() {
//                                            @Override
//                                            public boolean handleMessage(@NonNull Message msg) {
////                                                Bitmap bb = BitmapFactory.decodeFile(finalPath);
//                                                ((ImageView) finalConvertView.findViewById(R.id.imageNet)).setImageDrawable(finalM);
//                                                return false;
//                                            }
//                                        }).sendEmptyMessage(0);
//                                    }
//                                }.start();
                                final View finalConvertView1 = convertView;
//                                x.image().loadDrawable(finalUrl, null, new Callback.CommonCallback<Drawable>() {
//                                    @Override
//                                    public void onSuccess(Drawable result) {
//                                        if(!finalUrl.contains("egg")){
//                                        ((ImageView) finalConvertView1.findViewById(R.id.imageNet)).setImageDrawable(result);
//                                        }
//                                    }
//
//                                    @Override
//                                    public void onError(Throwable ex, boolean isOnCallback) {
//
//                                    }
//
//                                    @Override
//                                    public void onCancelled(CancelledException cex) {
//
//                                    }
//
//                                    @Override
//                                    public void onFinished() {
//
//                                    }
//                                });
                                Picasso.with(getContext()).load(Uri.parse(url)).error(R.drawable.ic_launcher)
                                        .config(Bitmap.Config.RGB_565)
                                        .into(((ImageView) convertView.findViewById(R.id.imageNet)));


//                                ((ImageView) convertView.findViewById(R.id.imageNet))

                            } catch (Exception e) {
                                ShareAlert.shareAlert((Activity) getContext(), e.toString());
                            }
                        }
                        if (m.containsKey("actybody")) {

                            Map actybody = JsonToMapUtils.parseJsonToMap((String) m.get("actybody"));
                            String acty_date = (String) actybody.get("ACTY_DATE");

                            String date1 =
                                    acty_date.split(" 至 ")[0];
                            String date10 = date1.split(" ")[0];
                            String ampm = "";
                            String date11 = "";
                            if (date1.split(" ").length == 1) {

                            } else {
                                date11 = date1.split(" ")[1];
                                ampm = DateUtil.getAMPM(date11.split(":")[0]);
                            }
                            String tmpdate10 = new Date().getYear() + "/" + date10;
                            String week = "";
                            try {
                                week = DateUtil.dateToWeek(tmpdate10);
                            } catch (ParseException e) {
                            }
                            String rt = date10.replace("/", "月") + "日" + (ampm.equals("") ? "" : ("(" + week + ")" + ampm + date11)) + " ";
                            ((TextView) convertView.findViewById(R.id.name)).setText(rt + "\n" + (CharSequence) m.get(textField));
                        } else {
                            ((TextView) convertView.findViewById(R.id.name)).setText((CharSequence) m.get(textField));

                        }
                    }

                    return convertView;
                }
                //提交flag
                //创建界面屏蔽 显示界面屏蔽
                //创建ui入口 设标志
                //显示地段设标志
                //数据标志
                //数据标志
            });
        } else {
            ((BaseAdapter) lv.getAdapter()).notifyDataSetChanged();
        }
        lv.setVisibility(View.VISIBLE);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (clickCallback != null) {
                    clickCallback.setParam(FillUtil.this);
                    clickCallback.onCallback(parent, position);

                }
            }
        });
        if (finalcallback != null) {
            finalcallback.onCallback(null, null);
        }
        return this;
    }

    public Bitmap getImageBitmap(String url) {
        URL imgUrl = null;
        Bitmap bitmap = null;
        try {
            imgUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) imgUrl
                    .openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    public static void filllocal(ListView lv, List<String> liststring) {

        String big = "";

        for (String s : liststring) {
            big += ",[" + s +
                    "]";
        }

        big = big.substring(1);
        lv.setTag("fake:[" +
                big + "];layout:");
        int item_str_r_type_attr = R.layout.string_item;
        MapViewConf.with(lv.getContext()).source(liststring
                , lv).conf(MapViewConf.with(lv.getContext()).source(item_str_r_type_attr == -1 ? com.aliang.auto.R.layout.auto_string_item_choosable : item_str_r_type_attr)).toView();
    }

    @Override
    public AndroidInstance use(Object mp, Object... p) {
        return null;
    }

    public String textField = "text";
    public String imageField = "image";

    public FillUtil setTextField(String textField) {
        this.textField = textField;
        return this;
    }

    public FillUtil setImageField(String imageField) {
        this.imageField = imageField;
        return this;
    }
}
